package com.xju.ExampleSystem;

import java.io.FileInputStream;
import java.util.*;

/**
 * <h1>管理器</h1> 可以获取一个考试例子
 * 
 */
public class ExampleManager {
	private List<Question> questionList; // Questions List

	public void initExample() {
		questionList = new ArrayList<Question>();
		FileInputStream inputStream;
		try {
			inputStream = new FileInputStream(
					"./src/com/xju/ExampleSystem/Examples.txt");
			Scanner scanner = new Scanner(inputStream);
			while (scanner.hasNextLine()) {
				String tmp = scanner.nextLine();
				Question q = QuestionFactory(tmp);
				if (q != null)
					questionList.add(q);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public Example genrateExample() {
		return genrateExample(5);
	}

	private List<Integer> getRandomArray(int max, int count) {
		List<Integer> list = new ArrayList<Integer>();
		int c = 0;
		while (c < count) {
			Random random = new Random();
			int r = random.nextInt(max);
			if (!list.contains(r)) {
				list.add(r);
				c++;
			}
		}
		return list;
	}

	public Example genrateExample(int questionCount) {
		Example example = new Example();
		List<Question> list = new ArrayList<Question>();
		List<Integer> iList = getRandomArray(questionList.size(), questionCount);
		for (Integer i : iList) {
			list.add(questionList.get(i));
		}
		example.setqList(list);
		return example;
	}

	private Question QuestionFactory(String content) {
		if (content.length() > 1) {
			Question question = new Question();
			String[] arr = content.split("\\|");
			question.setContent(arr[0].trim());
			question.setAnswerA(arr[1].trim());
			question.setAnswerB(arr[2].trim());
			question.setAnswerC(arr[3].trim());
			question.setAnswerD(arr[4].trim());
			question.setRightAnswer(arr[5].trim());
			return question;
		}
		return null;
	}
}
